package main

import (
	"html/template"
	"net/http"
	"os"
	"path/filepath"
	"strings"

	"gitverse.ru/panarinv/tmplter"
)

var ADDR string = "127.0.0.1:43712"

func main() {
	if len(os.Args) == 2 {
		ADDR = os.Args[1]
	}
	prog := filepath.Base(os.Args[0])
	println("TMPLTER", ADDR, "(usage: "+prog+" host:port)")
	http.HandleFunc("/", handler)
	err := http.ListenAndServe(ADDR, nil)
	if err != nil {
		panic(err.Error())
	}
}

func handler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		t := template.Must(template.New("PAGE").Parse(PAGE))
		tmpltr := tmpltr{Tpl: DEF_TPL, Clc: DEF_CLC}
		err := t.Execute(w, tmpltr)
		if err != nil {
			panic(err.Error())
		}
	} else if r.Method == "POST" {
		tmpltr := tmpltr{
			Tpl: r.FormValue("tpl"),
			Clc: r.FormValue("clc")}

		// collection_name:
		//   row1:
		//     field1: value11
		//     field2: value12
		//     ...
		//   row2:
		//     field1: value21
		//     field2: value22
		//     ...
		//   ...
		clcs := map[string][]map[string]string{}

		clc_files := strings.Split(tmpltr.Clc, "\r\n\r\n")
		for _, clc_file := range clc_files {
			clc_file = strings.Trim(clc_file, " \r\n")
			lines := strings.Split(clc_file, "\r\n")
			clc_title := lines[0]
			clc_content := strings.Join(lines[1:], "\n")
			clc_items, err := tmplter.ReadCollection(clc_content, ',')
			if err != nil {
				tmpltr.Res = "COLLECTION ERROR: " + clc_title + ": " + err.Error()
				break
			}
			clcs[clc_title] = clc_items
		}

		if tmpltr.Res == "" {
			result, err := tmplter.ParseTemplate(tmpltr.Tpl, clcs, map[string]string{})
			if err == nil {
				tmpltr.Res = result
			} else {
				tmpltr.Res = "TEMPLATE ERROR: " + err.Error()
			}
		}

		t := template.Must(template.New("PAGE").Parse(PAGE))
		err := t.Execute(w, tmpltr)
		if err != nil {
			panic(err.Error())
		}
	} else {
		http.NotFound(w, r)
	}
}

type tmpltr struct {
	Tpl string
	Clc string
	Res string
}

var PAGE string = `<!DOCTYPE html>
<meta charset="utf-8"/>
<title>TMPLTER</title>
<h2>TMPLTER</h2>
<form method="post">
  <label for="tpl">Шаблон</label>
  <textarea name="tpl" id="tpl" style="width: 99%; height: 100px" autofocus
    >{{.Tpl}}</textarea>
  <label for="clc">Коллекции значений</label>
  <textarea name="clc" id="clc" style="width: 99%; height: 160px"
    >{{.Clc}}</textarea>
  <input type="submit" name="run" value="Выполнить"/>
</form>
<pre>{{.Res}}</pre>
`

var DEF_TPL = `Заголовок {{book.csv/}}{{book}}{{/book.csv}}{{dics.csv/}}
Словарь: "{{DicCaption}}"{{dicitems.csv/}}
  Элемент: "{{ItemCaption}}";{{/dicitems.csv}}{{/dics.csv}}
Все элементы:{{dicitems.csv/}}
  {{ItemCaption}}{{/dicitems.csv}}
Подвал`

var DEF_CLC = `
book.csv
book
Книга 1


dics.csv
DicName,DicCaption
Dic1,Словарь 1
Dic2,Словарь 2
Dic3,Словарь 3

dicitems.csv
DicName,ItemName,ItemCaption
Dic1,Item1,Элемент 1
Dic1,Item2,Элемент 2
Dic1,Item3,Элемент 3
Dic2,Item4,Элемент 4
Dic3,Item5,Элемент 5
Dic3,Item6,Элемент 6
`
